import repository from '../repository'
import storageService from './StorageService'
class ConsumerService {
  // 判断是否登录
  async isLogin () {
    const token = storageService.getItem('token')
    if (!token) {
      return false
    }
    const data = await repository.getConsumerInfo(token)
    if(data.code!=200){
      throw new Error( data.msg)
    }
    return data
  }

  // 获取当前登录用户信息（会对信息进行缓存）
  async getConsumerInfo () {
   
    const data = await repository.getConsumerInfo()
    console.log("=============")

    return data.data
  }

  // 进行登录
  async login (param) {
    const data = await repository.login(param)
    if(data.code!=200){
      throw new Error( data.msg)
    }
    storageService.putItem('token', data.data.token)
    return data.data
  }

  // 进行注册
  async register (params) {
    const data = await repository.register(params)
    if(data.code!=200){
      throw new Error( data.msg)
    }
    return data
  }

  // 获取当前登录用户默认收货信息
  async getDefaultDelivery () {
    const data = await repository.getConsumerDefaultDelivery()
    if(data.code!=200){
      throw new Error( data.msg)
    }
    return data.data
  }

  // 注销
  logout () {
    storageService.remove('token')
  }

  //绑定手机号
  async bindPhone(param){
    const data = await repository.bindPhone(param)
    if(data.code==500){
      throw new Error(data.msg)
    }
    return data.data
  }


  async uploadAvatar (fileList) {
    if (!fileList || fileList.length === 0) {
      throw new Error('上传头像失败:没有选择图片')
    }
    const formData = new FormData()
    formData.append('file', fileList[0])
    const data = await repository.uploadAvatar(formData)
   
    return data.data
  }

  async updateUserInfo (userInfo) {
    const data = await repository.updateUserInfo(userInfo)
    if(data.code!=200){
      throw new Error( data.msg)
    }
    return true
  }

  async updatePassword (old, newPassword) {
    const data = await repository.updatePassword(old, newPassword)
    if(data.code!=200){
      throw new Error( data.msg)
    }
    return true
  }
}
export default new ConsumerService()
